﻿using DevExpress.XtraEditors;
using DevExpress.XtraGrid;
using DevExpress.XtraGrid.Views.Grid;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using WorkflowCore2210A.Application.Dto;
using WorkflowCore2210A.Application.Enums;
using System.Reflection;
using B.MESUI.Login.EquipmentManagement.DTO;

namespace B.MESUI.Login.WorkflowCore.Form
{
    public partial class DesignForm : DevExpress.XtraEditors.XtraForm
    {

        private TextEdit txtDefinitionModelId;
        private GridControl gridFormFields;
        private GridView gridViewFormFields;
        private BindingList<FormField> formFieldsList;

        /// <summary>
        /// DefinitionId
        /// </summary>
        public string ID;
        /// <summary>
        /// 初始化的表单数据
        /// </summary>
        public List<FormField> FormFields;
        public DesignForm(string id, List<FormField> FormFields)
        {
            InitializeComponent();
            this.CenterToParent();
            this.ID = id;
            this.FormFields = FormFields;

            // 1. definitionModelId控件（已隐藏，不添加到界面）
            txtDefinitionModelId = new TextEdit
            {
                Text = id,
                ReadOnly = true,
                Dock = DockStyle.Top
            };
            // 不再添加到Controls
            // this.Controls.Add(txtDefinitionModelId);

            // 2. formFields表格
            gridFormFields = new GridControl { Dock = DockStyle.Fill };
            gridViewFormFields = new GridView();
            gridFormFields.MainView = gridViewFormFields;
            gridFormFields.ViewCollection.Add(gridViewFormFields);

            // 3. 绑定数据（反填初始化数据）
            if (FormFields != null)
                formFieldsList = new BindingList<FormField>(FormFields);
            else
                formFieldsList = new BindingList<FormField>();
            gridFormFields.DataSource = formFieldsList;

            // 4. 配置列
            gridViewFormFields.Columns.AddVisible("FieldName", "字段名");
            gridViewFormFields.Columns.AddVisible("DisplayFieldName", "显示名");

            // 字段类型下拉（用FieldTypeEnum枚举）
            var colFieldType = gridViewFormFields.Columns.AddVisible("FieldType", "字段类型");
            var lookUpEdit = new DevExpress.XtraEditors.Repository.RepositoryItemLookUpEdit();

            // 构建数据源，首行加“请选择”
            var dataSource = new List<object>
            {
                new { Value = (FieldTypeEnum?)null, Description = "请选择" }
            };
            dataSource.AddRange(
                Enum.GetValues(typeof(FieldTypeEnum))
                    .Cast<FieldTypeEnum>()
                    .Select(e => new
                    {
                        Value = (FieldTypeEnum?)e,
                        Description = GetEnumDescription(e)
                    })
            );

            lookUpEdit.DataSource = dataSource;
            lookUpEdit.DisplayMember = "Description";
            lookUpEdit.ValueMember = "Value";
            lookUpEdit.NullText = "请选择"; // 编辑时显示
            lookUpEdit.ShowHeader = false; // 不显示下拉表头
            lookUpEdit.ShowFooter = false; // 不显示下拉底部
            lookUpEdit.Columns.Clear();
            lookUpEdit.Columns.Add(new DevExpress.XtraEditors.Controls.LookUpColumnInfo("Description", 0)); // 只显示描述

            colFieldType.ColumnEdit = lookUpEdit;

            // 获取枚举Description的方法
             string GetEnumDescription(FieldTypeEnum value)
            {
                var field = value.GetType().GetField(value.ToString());
                var attr = field.GetCustomAttributes(typeof(System.ComponentModel.DescriptionAttribute), false)
                                .FirstOrDefault() as System.ComponentModel.DescriptionAttribute;
                return attr != null ? attr.Description : value.ToString();
            }

            // 允许新增、删除行
            gridViewFormFields.OptionsView.NewItemRowPosition = DevExpress.XtraGrid.Views.Grid.NewItemRowPosition.Bottom;
            gridViewFormFields.OptionsBehavior.Editable = true;

            this.Controls.Add(gridFormFields);

            // 删除按钮
            var btnDelete = new SimpleButton { Text = "删除选中行", Dock = DockStyle.Bottom };
            btnDelete.Click += (s, e) =>
            {
                var row = gridViewFormFields.FocusedRowHandle;
                if (row >= 0)
                    gridViewFormFields.DeleteRow(row);
            };
            this.Controls.Add(btnDelete);

            // 保存按钮
            var btnSave = new SimpleButton { Text = "保存", Dock = DockStyle.Bottom };
            btnSave.Click += async (s, e) =>
            {
                // 1. 获取 definitionModelId
                var definitionModelId = this.ID;

                // 2. 获取表格数据
                var formFields = formFieldsList.ToList();

                // 3. 组装请求对象
                var request = new
                {
                    definitionModelId = definitionModelId,
                    formFields = formFields.Select(f => new
                    {
                        fieldName = f.FieldName,
                        displayFieldName = f.DisplayFieldName,
                        fieldType = (int)f.FieldType // 枚举转int
                    }).ToList()
                };

                // 4. 序列化为JSON
                var json = Newtonsoft.Json.JsonConvert.SerializeObject(request);

                // 5. 发送POST请求
                using (var client = new System.Net.Http.HttpClient())
                {
                    var content = new System.Net.Http.StringContent(json, Encoding.UTF8, "application/json");
                    var response = await client.PostAsync($"{BaseUrl.WorkflowUrl}Workflow/SaveFormTemplate", content);
                    if (response.IsSuccessStatusCode)
                    {
                        MessageBox.Show("保存成功！");
                    }
                    else
                    {
                        MessageBox.Show("保存失败：" + response.ReasonPhrase);
                    }
                }
                this.DialogResult = DialogResult.OK;
                this.Close();
            };
            this.Controls.Add(btnSave); // 注意顺序，先加btnSave再加btnDelete，btnDelete会在最下方
        }
    }
}